var bg = chrome.extension.getBackgroundPage();
// console.log("focusTypeValue",focusTypeValue , defaultFocusType , defaultFocusType.toString())
var layer = layui.layer,
    table = layui.table;
    form = layui.form;
var datalist = [
    // { stockCode:'603212',stockName:'赛伍技术' },
    // { stockCode:'000911',stockName:'南宁糖业' },
    // { stockCode:'300343',stockName:'联创股份' },
    // { stockCode:'002081',stockName:'金螳螂' },
    // { stockCode:'600518',stockName:'康美' },
    // { stockCode:'600737',stockName:'中粮糖业' },
    // { stockCode:'300376',stockName:'易事特' },
    // { stockCode:'300319',stockName:'麦捷科技' },
    // { stockCode:'002127',stockName:'南极电商' },
    // { stockCode:'000603',stockName:'盛达资源' },
    // { stockCode:'000027',stockName:'深圳能源' },
    // { stockCode:'002228',stockName:'合兴包装' },
    // { stockCode:'002739',stockName:'万达电影' },
    // { stockCode:'600139',stockName:'西部资源' },
    // { stockCode:'000338',stockName:'潍柴动力' },
    // { stockCode:'600699',stockName:'均胜电子' },
    // { stockCode:'002375',stockName:'亚夏股份' },
    // { stockCode:'600496',stockName:'精工钢构' },
    // { stockCode:'000802',stockName:'北京文化' },
];
var unusualTypes = [
    // 8201 , 8202 , 8193 , 8193 , 4 , 32 , 64 , 8207 , 8209
    // , 8211 , 8213 , 8215 , 8204 , 8203 , 8194 , 8 , 16 , 128 , 8208 , 8210 , 8212 ,
    // 8214 , 8216 
]

// http://www.uimaker.com/layui/doc/modules/form.html#val
$(document).on("click", "input", function () {
    console.log('change')
})
function getUnusualTypes(){
    return unusualTypes
}
console.log("localstorage",localStorage)

function UpdateCfg(){
    var setting = bg.getSetting()
    // 监听类型 
    // console.log( "复选框 unusualTypes", $("#unusualTypeForm [name]").serializeArray() );
    var unusualTypes = $("#unusualTypeForm [name]").serializeArray()
    var filtTypes = ( unusualTypes.length>0 ) ? unusualTypes.map(function(item){ return item.value }) : [];
    
    // 订阅
    var subscribeForm = $("#subscribeForm [name]").serializeArray()
    var subscribeCfg = {}
    if( subscribeForm.length>0 ){
        subscribeForm.map(function(item){ 
            subscribeCfg[item.name] = item.value;
        })
    }
    console.log("subscribeCfg",subscribeCfg)
    // 平台
    // console.log( "单选框 stockType", $("#detailSetting [name]").serializeArray() );
    var platform = $("#detailSetting [name]").serializeArray();
    var stockType = ( platform.length>0 ) ? platform[0].value: '';
    // focus
    setting.filtTypes = filtTypes;
    setting.stockType = stockType;
    setting.subscribeFilter = subscribeCfg;
    setting.focusList = datalist;
    console.log( "unusualSetting" , localStorage.getItem("unusualSetting") , setting )
    if( !localStorage.getItem("unusualSetting") || JSON.stringify(setting) != localStorage.getItem("unusualSetting")  ){
        localStorage.setItem("unusualSetting",JSON.stringify(setting))
        var version = localStorage.getItem("unusualSettingVersion") ? parseInt( localStorage.getItem("unusualSettingVersion") ) + 1 : 0 ;
        localStorage.setItem( "unusualSettingVersion" , version )
        bg.emitUpateSetting();
    }
    layer.msg('更新配置完成');
}
$(document).on("click","#updateBtn",function(){
    console.log("click updateBtn")
    UpdateCfg();
})
console.log("layer",window)

// 页面初始化
function pageInit(){
    var setting =  bg.getSetting()
    // console.log( "setting" , setting )
    datalist = setting.focusList ;
    unusualTypes = setting.filtTypes;
    var checks = unusualTypes.map(function(item){ return parseInt( item ) });
    // console.log( "checkBox" , $('#unusualTypeList input:checkbox') )
    var checkBoxs = $('#unusualTypeList input:checkbox')
    checkBoxs.each(function(i){
        var el = checkBoxs[i];
        console.log("item", $(this).val() )
        if( checks.indexOf( parseInt( $(this).val() ) ) >-1 ){
            $(this).prop("checked", true)
        }
    });
    form.val("subscribeFormLayFil", setting.subscribeFilter );
    form.val("unusualDetailFormLayFil",{ stockPlatform: setting.stockType } );

    // 延迟渲染(使DOM先完成渲染,算出宽度),避免渲染出现水平滚动条
    setTimeout(function(){
        tableUpdate();          // 渲染表格z
    } , 0 )
    // 更新渲染页面
    // form.render();
}
// //监听多选框点击事件  主要是通过 lay-filter="switchTest"  来监听
// form.on('checkbox', function (data) {
//     console.log( data , form , $("#unusualTypeForm [name]").serializeArray() );//打印当前选择的信息
// });


//工具条事件
table.on('tool(test)', function(obj){   //  注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data;                //  获得当前行数据
    var layEvent = obj.event;           //  获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
    var tr = obj.tr;                    //  获得当前行 tr 的 DOM 对象（如果有的话）

        // var tr = obj.tr; //获得当前行 tr 的DOM对象
    var $this = $(this);
    var tr = $this.parents('tr');
    var trIndex = tr.data('index');
    console.log(" 工具 " , obj , data , trIndex )
    if(layEvent === 'detail'){ //查看
        //do somehing
    } else if(layEvent === 'del'){ //删除
        layer.confirm(`真的删除 ${data.stockName} 么?`, function(index){
            // obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
            layer.close(index);
            datalist.splice( trIndex , 1 );
            tableUpdate();
            //向服务端发送删除指令
        });
    } else if(layEvent === 'edit'){ //编辑
        // console.log("edit", data)
        form.val("focusFormLayFil",{
            index: trIndex ,
            stockCode:data.stockCode ,
            focusType:data.focusType ,
            stockName:data.stockName
        } );
        $("#focusFormSubmit").text("更新")
        //同步更新缓存对应的值
        // obj.update({
        //     stockCode: '123'
        //     ,title: 'xxx'
        // });
    } else if(layEvent === 'LAYTABLE_TIPS'){
        layer.alert('Hi，头部工具栏扩展的右侧图标。');
    }
});

// 表格对象
var tableObj = undefined;
function tableRender(){
    //第一个实例
    tableObj = table.render({
        elem: '#demo'
        ,height: 312
        ,cols: [[ //表头
            {   field: '', title: '序号', fixed: 'left' ,
                templet: function(d){
                    // console.log(d);
                    return (d.LAY_INDEX);
                }
            }
            ,{field: 'stockCode', title: '股票代码' }
            ,{field: 'stockName', title: '股票名称' }
            ,{field: 'focusType', title: '类型',
                templet: function(d){
                    // console.log(d);
                    return focusTypeValue[ d.focusType ]
                }
            }
            ,{
                fixed: 'right',width: 200,
                align:'center', toolbar: '#barDemo'} //这里的toolbar值是模板元素的选择器
        ]],
        limit:200,              //  不设置,默认会只显示10条数据
        data:datalist
    });
}
// 更新table
function tableUpdate(){
    if(tableObj){
        tableObj.reload({ data:datalist })
    }else{ tableRender(); }
}
//  监听提交(第二个表格)
form.on('submit(formDemo)', function(obj){
    console.log("formDemo submit" , obj )
    var itemData = obj.field;
    var index = itemData.index;
    delete itemData.index;
    if( index || index ===0 ){
        datalist[index] = itemData
    }else{
        datalist.push( itemData );    
    }
    // layer.msg(JSON.stringify(obj.field));
    tableUpdate()
    focusFormReset()
    // return false;       // 清空表单
});
function focusFormReset(){
    // console.log("focusFormReset")
    form.val("focusFormLayFil",{
        index:'',
        focusType:defaultFocusType,
        stockCode:'',
        stockName:''
    } );
    $("#focusFormSubmit").text("添加")
    // form.render();
}
$(document).on("click","#focusFormReset",function(){
    console.log("重置")
    focusFormReset();
})
// form.on('input(formReset)', function(obj){
//     console.log("formDemo formReset" , obj )
//     return false;       // 清空表单
// });


pageInit()